package com.insightfullogic.java8.lilitest;

/**
 * @author lili
 * @description ${DESCRIPTION}
 * @create 2018-01-20 下午4:23
 * @since
 **/

//抄写依赖反转

import com.insightfullogic.java8.examples.chapter8.HeadingLookupException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

/**
 * {@link com.insightfullogic.java8.examples.chapter8.DependencyInversionPrinciple}
 */
public class DIP {

    public static interface HeadingFinder {
        public List<String> findHeadings(Reader reader);
    }

    public static class NoDIP implements HeadingFinder {


        @Override
        public List<String> findHeadings(Reader input) {
            try (BufferedReader br = new BufferedReader(input)) {
                return br.lines().filter(line -> line.endsWith(":"))
                        .map(line -> line.substring(0, line.length() - 1))
                        .collect(toList());
            } catch (IOException e) {
                throw new HeadingLookupException(e);
            }
        }
    }


    public static class HaveDIP implements HeadingFinder {

        @Override
        public List<String> findHeadings(Reader reader) {
            return withLineOf(reader,
                    lines -> lines.filter(line -> line.endsWith(":"))
                            .map(line -> line.substring(0, line.length() - 1)).collect(toList())
                    , HeadingLookupException::new);
        }


        private <T> T withLineOf(Reader input,
                                 Function<Stream<String>, T> handler,
                                 Function<IOException, HeadingLookupException> err) {
            try (BufferedReader br = new BufferedReader(input)) {
                return handler.apply(br.lines());
            } catch (IOException e) {
                throw err.apply(e);
            }


        }
    }
}
